import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-12
 * Time: 8:34
 */
class MyThreadPool {
    private int max = 0;
    private BlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(1000);
    private List<Thread> threadList = new ArrayList<>();

    public MyThreadPool(int core, int max) {
        this.max = max;
        for (int i = 0; i < core; i++) {
            Thread t = new Thread(() -> {
                try {
                    while (true) {
                        Runnable runnable = queue.take();
                        runnable.run();
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            });
            t.start();
            threadList.add(t);
        }
    }

    public void submit(Runnable runnable) throws InterruptedException {

        queue.put(runnable);
        if (queue.size() >= 500 && threadList.size() <= max) {
            Thread t = new Thread(() -> {

                while (true) {
                    Runnable runnable2 = null;
                    try {
                        runnable2 = queue.take();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    runnable2.run();
                }
            });
            t.start();
            threadList.add(t);


        }
    }
}
public class Demo1 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool=new MyThreadPool(10,20);
        for (int i = 0; i < 10000; i++) {
            int id=i;
          myThreadPool.submit(new Runnable() {
              @Override
              public void run() {
                  System.out.println("hello "+id+", "+Thread.currentThread().getName());
              }
          });
        }
    }
}
